package com.tao.base.app.initer;

import android.content.Context;
import android.os.Process;

import com.github.anrwatchdog.ANRError;
import com.github.anrwatchdog.ANRWatchDog;
import com.tao.base.app.config.PathConfig;
import com.tao.logger.log.Logger;
import com.tao.mvpbaselibrary.app.crash.CrashHandler;
import com.tao.mvpbaselibrary.app.crash.OnCrashListener;
import com.tao.mvpbaselibrary.basic.manager.AppManager;
import com.tao.utils.TimeSimpleUtil;
import com.tao.utilslib.log.CrashUtil;
import com.tao.utilslib.log.logsave.LogSaveManager;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.umcrash.UMCrash;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

public class CrashIniter {
    private static CrashIniter crashIniter = new CrashIniter();
    private ANRWatchDog anrWatchDog;
    Context context;

    private CrashIniter() {
    }

    public static CrashIniter getInstance() {
        return crashIniter;
    }

    public void init(Context context) {
        this.context = context.getApplicationContext();

        CrashHandler.getExceptionHandler().setCrashListener(new OnCrashListener() {
            @Override
            public void onMainCrash(String strException, Throwable e) {

                UMCrash.generateCustomLog(e, "onMainCrash");
                CrashReport.postCatchedException(e);
                saveCrashLog(e);
                Logger.e("抱歉，程序出现了一个异常——前台");
                e.printStackTrace();
                waitTime(2, TimeUnit.SECONDS);
            }

            @Override
            public void onBackgroundCrash(String strCrashLog, Throwable e) {

                UMCrash.generateCustomLog(e, "onBackgroundCrash");

                CrashReport.postCatchedException(e);
                saveCrashLog(e);
                Logger.e("抱歉，程序出现了一个异常——后台");
                e.printStackTrace();

                waitTime(2, TimeUnit.SECONDS);
            }
        });

        anrWatchDog = new ANRWatchDog(4000);
        anrWatchDog.start();
        anrWatchDog.setANRListener(new ANRWatchDog.ANRListener() {
            @Override
            public void onAppNotResponding(ANRError e) {
                CrashReport.postCatchedException(e);
                saveCrashLog(e);
                waitTime(2, TimeUnit.SECONDS);
                AppManager.getAppManager().finishAllActivity();
                try {
                    Process.killProcess(Process.myPid());
                } catch (Exception a) {
                    a.printStackTrace();
                    CrashReport.postCatchedException(e);
                    saveCrashLog(e);
                    waitTime(2, TimeUnit.SECONDS);
                }
            }
        });
        anrWatchDog.setANRInterceptor(new ANRWatchDog.ANRInterceptor() {
            @Override
            public long intercept(long duration) {
                return 0;
            }
        });
    }

    private void waitTime(int time, TimeUnit seconds) {
        try {
            seconds.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void saveCrashLog(Throwable e) {

        try {
            Calendar instance = Calendar.getInstance();
            int month = instance.get(Calendar.MONTH) + 1;
            int yera = instance.get(Calendar.YEAR);
            int day = instance.get(Calendar.DAY_OF_MONTH);
            String path = PathConfig.getCrashLogPath() + yera + "年/" + month + "月/" + day + "日/" + "crash-" + TimeSimpleUtil.TimeNowWithFormat() + "-" + System.currentTimeMillis() + ".txt";

            LogSaveManager.instance().logServer(path).log(CrashUtil.getErrorMessages(context, e));

        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
